package idbx

import (
	"gitee.com/tietang/terrace-go/v2/base"
	"gitee.com/tietang/terrace-go/v2/base/starter/ilogrus"
	_ "github.com/go-sql-driver/mysql"
	log "github.com/sirupsen/logrus"
	"github.com/tietang/dbx"
	"github.com/tietang/props/v3/kvs"
)

//Dbx SQL数据库ORM框架实例
var database *dbx.Database

func DbxDatabase() *dbx.Database {
	base.Check(database)
	return database
}

func RegisterTable(model interface{}, tableName string) {
	database.RegisterTable(model, tableName)
}

//配置示列：
//[mysql]
//driverName = mysql
//;host = 192.168.232.175:3306
//host = 127.0.0.1:3306
//;host = 172.16.1.248:3306
//database = po
//user = root
//password = 111111
//;连接池配置
//connMaxLifetime = 12h
//maxIdleConns = 1
//maxOpenConns = 3
//loggingEnabled = true
//;数据源参数配置
//options.charset = utf8
//options.parseTime = true
//options.loc = Local
type DbxDatabaseStarter struct {
	base.BaseStarter
	ConfigPrefix string
	settings     dbx.Settings
}

//初始化DbxDatabase ，并设置全局DbxDatabase
func (s *DbxDatabaseStarter) Setup(ctx base.StarterContext) {
	conf := ctx.Props()
	settings := dbx.Settings{}
	if s.ConfigPrefix == "" {
		s.ConfigPrefix = "mysql"
	}
	err := kvs.Unmarshal(conf, &settings, s.ConfigPrefix)
	if err != nil {
		panic(err)
	}
	log.Debugf("%+v", settings)
	log.Debugf("mysql.ConnectionURL: %s", settings.ShortDataSourceName())
	database, err = dbx.Open(settings)
	if err != nil {
		panic(err)
	}
	database.SetLogger(ilogrus.NewDbxLogrusLogger())
	s.settings = settings
}

func (s *DbxDatabaseStarter) Stop(ctx base.StarterContext) {
	DbxDatabase().Close()
	log.Info(" dbx shutdown on：", s.settings.ShortDataSourceName())
}
